import { Injectable } from '@angular/core';
// import { Config } from './config';
import { environment } from "./environment";
import { Http } from '@angular/http';
import { AuthHttp } from 'angular2-jwt';
import { AlertController, LoadingController, ToastController, App, Events } from 'ionic-angular';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/timeout';
import 'rxjs/add/operator/finally';
import 'rxjs/add/observable/throw';
import { Observable } from 'rxjs/Rx';
import { Storage } from '@ionic/storage';
import { LoginPage } from '../pages/login/login';
import _ from 'lodash';

// interface HttpClientConifg {
// 	isShowLoading?: boolean;
// 	isAlterError?: boolean;
// 	isAuthHttp?: boolean;
// 	loadingText?: string;
// 	isReturnOriginal?: boolean;
// }
interface HttpClientConifg {
	isShowLoading?: boolean;
	isAlterError?: boolean;
	isAuthHttp?: boolean;
	loadingText?: string;
	url?: string;
	timeout?: number;
}

@Injectable()
export class HttpClient {
	constructor(
		// public config: Config,
		public authHttp: AuthHttp,
		public http: Http,
		public loadingCtrl: LoadingController,
		public alertCtrl: AlertController,
		public appCtrl: App,
		public toastCtrl: ToastController,
		public storage: Storage,
		public events: Events
	) { }

	postHandler(PostBody: any, _postConfig: any) {
		// 创建加载框
		console.log(PostBody)
		let loading: any, _httpClient;
		if (_postConfig.isShowLoading) {
			loading = this.loadingCtrl.create({
				content: _postConfig.loadingText,
				// dismissOnPageChange: true
			});
			//window['gfoa_loading'] = loading;
			loading.present();
		}
		if (_postConfig.isAuthHttp) {
			_httpClient = this.authHttp;
		} else {
			_httpClient = this.http;
		}
		return _httpClient.post(_postConfig.url, PostBody).timeout(_postConfig.timeout).map(res => res.json()).catch(err => {
			// if(_.find(this.config.loadingIRM,{method:PostBody.method}))this.events.publish("loadingQJTDatas");
			if (PostBody.method == "getExceptionRuleDetail") this.events.publish("loadingBCWDatas");
			console.info('--err---');
			console.info(err);
			var errmsg: any = {};
			if (_.isError(err)) {
				//err['status'] = 500;
				if (err.name == 'TimeoutError') {
					errmsg.error = '请求超时,请稍后重试!';
				} else {
					errmsg.error = err.message;
				}
			} else {
				errmsg = err.json();
			}
			console.info(errmsg);
			let tips = '';
			if (err.status == 0) {
				tips = '网络连接出错,请检查网络状态';
			} else if (err.status == 401) {
				tips = errmsg.error;
				this.storage.remove('id_token').then(() => {
					// 跳转到登录
					this.appCtrl.getRootNav().setRoot(LoginPage);
				});
			} else if (err.status == 500) {
				tips = errmsg.error;
			} else {
				tips = '系统发生一个错误,请稍后重试!';
			}
			// let toast = this.toastCtrl.create({
			// 	message: tips,
			// 	duration: 2000,
			// 	position: 'middle'
			// });
			// toast.present(toast);

			// 判断是否需要弹出错误提示、并且三秒内只能弹出一个提示
			let lastAlertTime = sessionStorage.getItem("lastAlertTime");
			lastAlertTime = lastAlertTime ? lastAlertTime : '0';
			let nowAlertTime = new Date().getTime();
			if (_postConfig.isAlterError && ((nowAlertTime - parseInt(lastAlertTime)) > 3000)) {
				sessionStorage.setItem("lastAlertTime", nowAlertTime + '');
				let alert = this.alertCtrl.create({
					title: '提示',
					subTitle: tips,
					buttons: ['确认']
				});
				alert.present();
			}
			return Observable.of(null);
		}).finally(() => {
			if (_postConfig.isShowLoading) {
				loading.dismiss();
			}
			console.info('--finally---');
		});
	};

	post(PostBody: any, postConfig?: HttpClientConifg) {
		// 初始化配置
		let defaultPostConfig = {
			isShowLoading: true,
			isAuthHttp: true,
			isAlterError: true,
			loadingText: environment.loadingText,
			url: environment.server + "api/v1/",
			timeout: environment.timeout
		}
		let _postConfig = _.assignIn(defaultPostConfig, postConfig);
		return this.postHandler(PostBody, _postConfig);
	}
}
